package com.webshop.account.service.impl;

import com.webshop.account.service.AccountService;
import com.xphsc.easyjdbc.EasyJdbcTemplate;
import com.xphsc.easyjdbc.builder.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by LBG on 2019/6/23.
 */
@Component("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private EasyJdbcTemplate easyJdbcTemplate;

    @Override
    public Map<String, Object> doLogin(String userName, String password) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 1);
        StringBuffer loginSql = new StringBuffer();
        loginSql.append("select * from ims_users u");
        loginSql.append(" where u.username = ? ");
        loginSql.append(" and u.password = ? ");
        Object[] userParams = {userName, password};
        List<Map<String, Object>> userList = easyJdbcTemplate.find(loginSql.toString(), userParams);
        Map<String, Object> user;
        if (CollectionUtils.isEmpty(userList)) {
            map.put("msg", "用户名或密码错误！");
            return map;
        }
        user = userList.get(0);
        if (user != null) {
            StringBuffer userInfoSql = new StringBuffer();
            userInfoSql.append("select * from ims_users_profile ");
            userInfoSql.append("where uid = ? ");
            Object[] userInfoParams = {user.get("uid")};
            List<Map<String, Object>> userInfoList = easyJdbcTemplate.find(userInfoSql.toString(), userInfoParams);
            if (!CollectionUtils.isEmpty(userInfoList)) {
                map.put("code", 0);
                map.put("userInfo", userInfoList.get(0));
                return map;
            }
        }

        return map;
    }

    @Override
    public Map<String, Object> getVerificationCode(String phoneNum) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);


        if (isRegisted(phoneNum)) {
            map.put("code", 1);
            map.put("msg", "此手机号已注册！");
            return map;
        }

        StringBuffer veriSql = new StringBuffer();
        veriSql.append("select verifycode from ims_uni_verifycode ");
        veriSql.append("where receiver = ? and createtime >= ? and total = ? ");
        veriSql.append("order by createtime desc ");
        long time = new Date().getTime() - 5 * 60 * 1000;
        List<Map<String, Object>> maps = easyJdbcTemplate.find(veriSql.toString(), phoneNum, new Timestamp(time), 0);
        String verifyCode = "";
        if (CollectionUtils.isEmpty(maps)) {
            //生成新的验证码，存入数据库，并返回前台
            verifyCode = randomCode();
            map.put("verifyCode", verifyCode);
            SQL insertSql = new SQL();
            insertSql.INSERT_INTO("ims_uni_verifycode")
                    .VALUES("receiver", "?").VALUES("verifycode", "?")
                    .VALUES("total", "?").VALUES("createtime", "?");
            easyJdbcTemplate.insert(insertSql, phoneNum, verifyCode, 0, new Timestamp(new Date().getTime()).toString());
        } else {
            Map<String, Object> veriMap = maps.get(0);
            map.putAll(veriMap);
        }
        return map;
    }

    @Override
    public Map<String, Object> testVerificationCode(String phoneNum, String veriCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);

        StringBuffer veriSql = new StringBuffer();
        veriSql.append("select 1 from ims_uni_verifycode ");
        veriSql.append("where receiver = ? and createtime >= ? and total = ? and verifycode = ? ");
        veriSql.append("order by createtime desc ");
        long time = new Date().getTime() - 30 * 60 * 1000;
        int count = easyJdbcTemplate.count(veriSql.toString(), phoneNum, new Timestamp(time), 0, veriCode);
        if (count == 0) {
            map.put("code", 1);
            map.put("msg", "验证码已失效！");
            return map;
        }
        StringBuffer updateSql = new StringBuffer();
        updateSql.append("update ims_uni_verifycode set total = ? ");
        updateSql.append("where receiver = ? and createtime >= ? and total = ? and verifycode = ? ");
        easyJdbcTemplate.getJdbcTemplate().update(updateSql.toString(), 1, phoneNum, new Timestamp(time), 0, veriCode);
        return map;
    }

    @Override
    public Map<String, Object> registerAccount(String phoneNum, String password, String veriCode) {
       /* Map<String, Object> result = testVerificationCode(phoneNum, veriCode);
        int code = (int) result.get("code");
        if (code == 1) {
            return result;
        }*/
        Map<String, Object> result = new HashMap<String, Object>();
        if (isRegisted(phoneNum)) {
            result.put("code", 1);
            result.put("msg", "此手机号已注册！");
            return result;
        }
        StringBuffer insertSql = new StringBuffer();
        insertSql.append("insert into ims_users (username,password) values(?,?)");
        easyJdbcTemplate.getJdbcTemplate().update(insertSql.toString(), phoneNum, password);
        result.put("code", 0);
        return result;
    }

    private String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    private boolean isRegisted(String phoneNum) {
        StringBuffer accountSql = new StringBuffer();
        accountSql.append("select 1 from ims_users  where username = ? ");
        int count = easyJdbcTemplate.count(accountSql.toString(), phoneNum);
        return count > 0;
    }
}
